// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";

// 引入组件
// import Home from '@/pages/Home'
import Search from '@/pages/Search'
import Login from '@/pages/Login'
import Register from '@/pages/Register'
import Detail from '@/pages/Detail'
import AddCartSuccess from '@/pages/AddCartSuccess'
import ShopCart from '@/pages/ShopCart'
import Trade from "@/pages/Trade";
import Pay from "@/pages/Pay.vue";
import PaySuccess from "@/pages/PaySuccess.vue"
import Center from "@/pages/Center.vue";
import MyOrder from "@/pages/MyOrder.vue";
import GroupOrder from "@/pages/GroupOrder.vue";

//引入store
import store from "@/store";


//先把VueRouter原型对象的push|replace，先保存一份
let originPush = VueRouter.prototype.push; 
let originReplace = VueRouter.prototype.replace; 
//重写push|replace
VueRouter.prototype.push = function(location,resolve,reject){
     if(resolve && reject){
        originPush.call(this,location,resolve,reject)
     }else{
        originPush.call(this,location,()=>{},()=>{})
     }
}
VueRouter.prototype.replace = function(location,resolve,reject){
    if(resolve && reject){
      originReplace.call(this,location,resolve,reject)
    }else{
      originReplace.call(this,location,()=>{},()=>{})
    } 
}

//路由懒加载
/* 当打包构建应用时，JavaScript 包会变得非常大，影响页面加载。
   如果我们能把不同路由对应的组件分割成不同的代码块，然后当路由被访问的时候才加载对应组件，这样就会更加高效。 
*/ 
// const foo = ()=>{
//    console.log(123456);
//    return import('@/pages/Home')
// }
//component: foo

// 创建并暴露一个路由器
const router = new VueRouter({
    routes:[
      //项目启动定位到首页  
      { 
        path:'*',
        redirect:'/home'
      },
      {
        path:'/home',
        // component:Home,
        component:() => import('@/pages/Home'),
        meta:{show:true}
      },
      {
        name:'Search',
        path:'/search/:keyword?', 
        component:Search,
        meta:{show:true}
      },
      {
        path:'/login',
        component:Login,
        meta:{show:false}
      },
      {
        path:'/register',
        component:Register,
        meta:{show:false}
      },
      {
        path:'/detail/:skuid',
        component:Detail,
        meta:{show:true}
      },
      {
        name:'AddCartSuccess',
        path:'/addCartSuccess',
        component:AddCartSuccess,
        meta:{show:true}
      },
      {
        name:'ShopCart',
        path:'/shopCart',
        component:ShopCart,
        meta:{show:true}
      },
      {
        name:'Trade',
        path:'/trade',
        component:Trade,
        meta:{show:true},
        /* 只能从购物车界面, 才能跳转到交易界面 */
        beforeEnter (to, from, next) {
          if (from.path === '/shopCart') {
            next()
          } else {
            next('/shopcart')
          }
        }
      },
      {
        name:'Pay',
        path:'/pay',
        component:Pay,
        meta:{show:true},
        /* 只能从交易界面, 才能跳转到支付界面 */
        beforeEnter (to, from, next) {
          if (from.path==='/trade') {
            next()
          } else {
            next('/trade')
          }
        }
      },
      {
        name:'PaySuccess',
        path:'/paySuccess',
        component:PaySuccess,
        meta:{show:true}
      },
      {
        path: '/center',
        component: Center,
        children: [
          {
            path: 'myOrder',
            component: MyOrder,
          },
          {
            path: 'groupOrder',
            component: GroupOrder,
          },
          {
            path: '',
            redirect: 'myOrder' //默认重定向到【我的订单】
          }
        ]
      },
    ],
    //滚动行为
    scrollBehavior(to, from, savedPosition) {
        //返回的这个y=0，代表的滚动条在最上方
        return { y: 0 };
    },
})

//全局前置守卫：初始化时执行、每次路由切换前执行
router.beforeEach(async (to,from,next)=>{
      let token  = store.state.user.token;
      let name = store.state.user.userInfo.name;  
      //已经登录而且还想去登录------不行
      if(token){
          if(to.path=="/login" || to.path=='/register'){
              next('/'); //首页
          }else{
              //已经登陆了,访问的是非登录与注册
              //登录了且拥有用户信息放行
              if(name){
                next();
              }else{
                //登陆了且没有用户信息
                //在路由跳转之前获取用户信息且放行
                try {
                    await store.dispatch('user/getUserInfo');
                    next();
                } catch (error) {
                    //token失效重新登录
                    await store.dispatch('user/userLogout');
                    next('/login')
                }
              }
          }   
      }else{
          //未登录：不能去交易【trade】、不能去支付相关【pay|paySuccess】、不能去个人中心【center】
          //未登录去上面这些路由-----登录
          let toPath = to.path;
          if(toPath.indexOf('/trade')!= -1 || toPath.indexOf('/pay') !=-1 || toPath.indexOf('/center')!=-1){
            //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
            next('/login?redirect='+toPath);
          }else{
            //去的不是上面这些路由（home|search|shopCart）---放行
            next();
          }
      }        
})


export default router